package com.xln.furns.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public abstract class BasicServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //解决中文乱码问题
        req.setCharacterEncoding("UTF-8");

        //System.out.printf("BasicServlet doPost");

        String action = req.getParameter("action");
        Method method = null;
        //使用反射，获取当前对象的方法
        //使用反射，获取当前对象的方法[老韩解读

        //1.this就是请求的Servlet实例（tomcat底层帮忙创建的实例），this动态变化，不能new
        //2.declaredWethod方法对象就是当前请求的servlet对应的" action名字”的方法,该方法对象method
        //是变化的，根据用户请求
        //3.使用模板模式+反射+动态机制==>简化多个if..
        //如果我们使用了模板模式+反射+动态绑定，要满足动作（action）的值(value)和方法名一致
        try {
            method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
